package com.xpc.filter;

import com.baomidou.mybatisplus.extension.api.R;
import com.xpc.filter.util.HttpContextUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Qinkuer
 * @version 1.0.0
 * @ProjectName UniversityGradeAdministrationSystem
 * @ClassName TokenInterceptor.java
 * @Description 拦截器. 用于拦截未登录用户
 * @createTime 2022年05月23日 12:49:00
 */
public class TokenInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        Subject subject = SecurityUtils.getSubject();
        if(subject.isAuthenticated()){
            return true;
        }

        setReturn(response,-1,"未登录");
        return false;
//        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

    }

    private static void setReturn(HttpServletResponse response, int code, String msg) throws IOException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtil.getOrigin());
        httpResponse.setCharacterEncoding("UTF-8");
        httpResponse.setStatus(400);
        response.setContentType("application/json;charset=utf-8");
        String json = JSON.toJSONString(R.failed(msg).setCode(code));
        httpResponse.getWriter().print(json);
    }
}
